package com.violet.mvpdemo.mvp.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.violet.constlib.Resource
import com.violet.mvpdemo.utils.MD5
import com.violet.repository.repository.IRepositoryManager
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.rxjava3.core.Observable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(): ViewModel() {

    @Inject
    lateinit var mIRepositoryManager: IRepositoryManager

    fun loadUser(): Observable<String> {
        return mIRepositoryManager.commRepository.getUser()
    }

    //协程使用方式1
    fun launchUser() = liveData(Dispatchers.IO) {
        emit(Resource.loading())
        delay(2000)
        try {
            val launchUser = mIRepositoryManager.commRepository.launchUser()
            emit(Resource.success(launchUser))
        }catch (e: Exception) {
            emit(Resource.error<String>(data = e.message, message = e.message?:""))
        }
    }

    //viewModelScope
    fun login(uname: String) {

        //已经绑定生命周期，main线程执行
        viewModelScope.launch(Dispatchers.Main) {

            //main线程代码
            val md5 = MD5.md5(uname)

            val user: String
            //切换到IO线程
            withContext(Dispatchers.IO) {
                //请求接口，访问网络，异步
                user = mIRepositoryManager.commRepository.login(md5)
            }

            //继续执行main线程代码
            print(user)
        }
    }

    fun test() {
        viewModelScope.launch(Dispatchers.Main) {

            Log.e("viewModelScope", "开始")

            withContext(Dispatchers.IO) {

                Log.e("viewModelScope", "执行异步代码")

                delay(1000)
            }

            Log.e("viewModelScope", "结束")
        }
    }


    override fun onCleared() {
        super.onCleared()
    }

}